package codeRandomThoughts.Test39组合总和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//难点在于输出的组合不能重复
public class Solution2 {
    List<Integer> path = new ArrayList<>();
    int pathSum = 0;
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates, target, 0);
        return result;
    }

    private void backtracking(int[] candidates, int target, int startIndex) {
        //回溯终止条件
        if (pathSum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        if (pathSum > target) return;

        //单层回溯逻辑
        for (int i = startIndex; i < candidates.length && pathSum + candidates[i] <= target; i++) {
            pathSum += candidates[i];
            path.add(candidates[i]);
            backtracking(candidates, target, i);
            pathSum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}
